import os
import re
import codecs

compressor = 'java -jar yuicompressor-2.4.7.jar'
compressPath = 'BDB-min/'
ziper = '7za.exe'

files = [ 'baidu/basic.js', 'baidu/du.css', 'patch/adblock.js', 'patch/patch.css', 'tieba/final.js', 'tieba/Encoder.js', 'tieba/Config.js', 'tieba/PostClass.js', 'tieba/Editor.js', 'tieba/startrun.js', 'tieba/HotKey.js', 'tieba/UUcode.js', 'tieba/css/js.css', 'tieba/css/common.css', 'tieba/css/day.css', 'tieba/css/config.css', 'tieba/css/night.css' ]

def compressAll(files):
    for item in files:
        compress(item)

# Compress a file from path to compressPath
def compress(path):
    os.system(compressor + ' ' + path + ' -o ' + compressPath + path)
    print(path + ' has been compress to ' + compressPath + path)

def zip(item):
    os.system(ziper + ' a -tzip ' + 'build.zip ' + item)
    print(item + ' has been zipped.\n')

def getVersion():
    fileHandler = codecs.open('manifest.json', 'r', encoding='utf-8')
    regExp = re.compile('\Wversion')
    for line in fileHandler.readlines():
        if regExp.search(line):
            fileHandler.close()
            print('Version info: ' + line)
            return(line)
    fileHandler.close()

def writeVersion(versionLine):
    rFileHandler = codecs.open(compressPath + 'manifest.json', 'r', encoding='utf-8')
    fileLines = rFileHandler.readlines()
    rFileHandler.close()
    wFileHandler = codecs.open(compressPath + 'manifest.json', 'w', encoding='utf-8')
    regExp = re.compile('\Wversion')
    for line in fileLines:
        if regExp.search(line):
            wFileHandler.write(versionLine)
            print('Build version has been updated.\n')
        else:
            wFileHandler.write(line)
    wFileHandler.close()


print('Build begin!\n')
versionLine = getVersion()
writeVersion(versionLine)
compressAll(files)
zip(compressPath)
print('Build finished.')
input()